<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '../../utils/sj-request'
import KnowledgePointTree from './KnowledgePointTree.vue'

// 定义props
const props = defineProps({
  subjectId: {
    type: Number,
    required: true
  },
  examPlan: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// 定义emit事件
const emit = defineEmits(['success', 'cancel'])

// 表单数据
const formData = reactive({
  name: props.examPlan?.name || '',
  subjectId: props.subjectId,
  description: props.examPlan?.description || '',
  details: [],
  isDraft: false, // 是否为草稿
  questionCount: props.examPlan?.questionCount || 0, // 试题数量
  totalScore: props.examPlan?.totalScore || 0 // 总分数
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入方案名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: false, message: '请输入方案描述', trigger: 'blur' },
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 表单引用
const formRef = ref(null)

// 加载状态
const loading = ref(false)

// 详情表单
const detailForm = reactive({
  questionOrder: 1,
  bigQuestionId: null,
  bigQuestionName: '', // 大题名称
  questionTypeId: null,
  questionTypeName: '', // 题型名称
  hardLevel: '中等', // 默认中等难度
  knowledgePointId: null,
  knowledgePointName: '', // 知识点名称
  score: 10
})

// 难度级别选项
const hardLevelOptions = ref([])

// 获取带试题数量的难度级别列表
const fetchHardLevels = async (bigQuestionId, questionTypeId) => {
  if (!bigQuestionId || !questionTypeId) {
    hardLevelOptions.value = []
    return
  }
  
  try {
    const res = await request({
      url: '/question/hard-levels',
      method: 'get',
      params: {
        bigQuestionId,
        questionTypeId
      }
    })
    
    if (res.code === 200) {
      hardLevelOptions.value = res.data || []
    } else {
      ElMessage.warning(res.message || '获取难度级别列表失败')
    }
  } catch (error) {
    console.error('获取难度级别列表失败:', error)
    ElMessage.error('获取难度级别列表失败')
  }
}

// 大题列表
const bigQuestionList = ref([])
// 题型列表
const questionTypeList = ref([])
// 知识点列表
const knowledgePointList = ref([])

// 对话框显示状态
const bigQuestionDialogVisible = ref(false)
const questionTypeDialogVisible = ref(false)
const knowledgePointDialogVisible = ref(false)

// 获取带试题数量的大题列表
const fetchBigQuestions = async () => {
  try {
    const { subjectId } = props
    const res = await request({
      url: `/big-question/subject/question-count/${subjectId}`,
      method: 'get'
    })
    
    if (res.code === 200) {
      bigQuestionList.value = res.data || []
    } else {
      console.error('获取大题列表返回错误:', res)
      ElMessage.warning(res.message || '获取大题列表失败')
    }
  } catch (error) {
    console.error('获取大题列表失败:', error)
    ElMessage.error('获取大题列表失败')
  }
}

// 获取带试题数量的题型列表
const fetchQuestionTypes = async (bigQuestionId) => {
  if (!bigQuestionId) {
    questionTypeList.value = []
    return
  }
  
  try {
    const res = await request({
      url: '/question-type/list-with-count',
      method: 'get',
      params: {
        bigQuestionId
      }
    })
    
    if (res.code === 200) {
      questionTypeList.value = res.data || []
    } else {
      ElMessage.warning(res.message || '获取题型列表失败')
    }
  } catch (error) {
    console.error('获取题型列表失败:', error)
    ElMessage.error('获取题型列表失败')
  }
}

// 获取带试题数量的知识点列表
const fetchKnowledgePoints = async (bigQuestionId, questionTypeId, hardLevel) => {
  if (!bigQuestionId || !questionTypeId || !hardLevel) {
    knowledgePointList.value = []
    return
  }
  
  try {
    const res = await request({
      url: '/knowledge-point/tree/question-count',
      method: 'get',
      params: {
        subjectId: props.subjectId,
        bigQuestionId,
        questionTypeId,
        hardLevel
      }
    })
    
    if (res.code === 200) {
      knowledgePointList.value = res.data || []
    } else {
      console.error('获取知识点列表返回错误:', res)
      ElMessage.warning(res.message || '获取知识点列表失败')
    }
  } catch (error) {
    console.error('获取知识点列表失败:', error)
    ElMessage.error('获取知识点列表失败')
  }
}

// 打开大题选择对话框
const openBigQuestionDialog = () => {
  bigQuestionDialogVisible.value = true
  // 确保每次打开对话框时都重新获取最新的大题列表
  fetchBigQuestions()
}

// 打开题型选择对话框
const openQuestionTypeDialog = () => {
  if (!detailForm.bigQuestionId) {
    ElMessage.warning('请先选择大题')
    return
  }
  questionTypeDialogVisible.value = true
  // 确保每次打开对话框时都重新获取最新的题型列表
  fetchQuestionTypes(detailForm.bigQuestionId)
}

// 打开知识点选择对话框
const openKnowledgePointDialog = () => {
  if (!detailForm.bigQuestionId) {
    ElMessage.warning('请先选择大题')
    return
  }
  if (!detailForm.questionTypeId) {
    ElMessage.warning('请先选择题型')
    return
  }
  if (!detailForm.hardLevel) {
    ElMessage.warning('请先选择难度')
    return
  }
  
  knowledgePointDialogVisible.value = true
  // 确保每次打开对话框时都重新获取最新的知识点树
  fetchKnowledgePoints(detailForm.bigQuestionId, detailForm.questionTypeId, detailForm.hardLevel)
}

// 选择大题
const selectBigQuestion = (bigQuestion) => {
  detailForm.bigQuestionId = bigQuestion.id
  detailForm.bigQuestionName = bigQuestion.name
  bigQuestionDialogVisible.value = false
  
  // 重置后续选择
  detailForm.questionTypeId = null
  detailForm.questionTypeName = ''
  detailForm.hardLevel = '中'
  detailForm.knowledgePointId = null
  detailForm.knowledgePointName = ''
  
  // 获取该大题下的题型列表
  fetchQuestionTypes(bigQuestion.id)
}

// 选择题型
const selectQuestionType = (questionType) => {
  detailForm.questionTypeId = questionType.id
  detailForm.questionTypeName = questionType.name
  questionTypeDialogVisible.value = false
  
  // 重置后续选择
  detailForm.hardLevel = '中'
  detailForm.knowledgePointId = null
  detailForm.knowledgePointName = ''
  
  // 获取该题型下的难度级别列表
  fetchHardLevels(detailForm.bigQuestionId, questionType.id)
}

// 选择知识点
const selectKnowledgePoint = (knowledgePoint) => {
  detailForm.knowledgePointId = knowledgePoint.id
  detailForm.knowledgePointName = knowledgePoint.name
  knowledgePointDialogVisible.value = false
}

// 计算试题数量和总分数
const calculateTotals = () => {
  // 计算试题数量
  formData.questionCount = formData.details.length
  
  // 计算总分数
  formData.totalScore = formData.details.reduce((total, item) => {
    return total + (item.score || 0)
  }, 0)
}

// 添加详情项
const addDetail = () => {
  // 验证必填项
  if (!detailForm.bigQuestionId) {
    ElMessage.warning('请选择大题')
    return
  }
  if (!detailForm.questionTypeId) {
    ElMessage.warning('请选择题型')
    return
  }
  if (!detailForm.knowledgePointId) {
    ElMessage.warning('请选择知识点')
    return
  }
  if (!detailForm.score || detailForm.score <= 0) {
    ElMessage.warning('请输入有效的分值')
    return
  }
  
  // 创建一个新的详情对象（深拷贝）
  const newDetail = JSON.parse(JSON.stringify(detailForm))
  
  // 添加到详情列表
  formData.details.push(newDetail)
  
  // 重置表单并增加序号
  detailForm.questionOrder = formData.details.length + 1
  
  // 更新试题数量和总分数
  calculateTotals()
  detailForm.bigQuestionId = null
  detailForm.bigQuestionName = ''
  detailForm.questionTypeId = null
  detailForm.questionTypeName = ''
  detailForm.knowledgePointId = null
  detailForm.knowledgePointName = ''
}

// 删除详情项
const removeDetail = (index) => {
  formData.details.splice(index, 1)
  
  // 重新排序
  formData.details.forEach((item, idx) => {
    item.questionOrder = idx + 1
  })
  
  // 更新下一个序号
  detailForm.questionOrder = formData.details.length + 1
  
  // 更新试题数量和总分数
  calculateTotals()
}

// 提交表单
const submitForm = async (isDraft = false) => {
  // 即使是草稿模式，也需要验证必填字段
  if (isDraft) {
    // 验证基本信息
    if (!formData.name) {
      ElMessage.warning('请输入方案名称')
      return
    }
    // 验证详情列表不为空
    if (formData.details.length === 0) {
      ElMessage.warning('请至少添加一个方案详情项')
      return
    }
    
    formData.isDraft = true
    loading.value = true
    try {
      // 提交表单数据
      emit('success', formData)
    } catch (error) {
      console.error('保存草稿失败:', error)
      ElMessage.error('保存草稿失败，请重试')
    } finally {
      loading.value = false
    }
    return
  }
  
  // 正式提交需要验证
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 验证详情列表不为空
      if (formData.details.length === 0) {
        ElMessage.warning('请至少添加一个方案详情项')
        return
      }
      
      loading.value = true
      try {
        formData.isDraft = false
        // 提交表单数据
        emit('success', formData)
      } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error('提交失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 保存为草稿
const saveAsDraft = () => {
  submitForm(true)
}

// 取消
const cancel = () => {
  emit('cancel')
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    formData.details = []
    detailForm.questionOrder = 1
    detailForm.bigQuestionId = null
    detailForm.bigQuestionName = ''
    detailForm.questionTypeId = null
    detailForm.questionTypeName = ''
    detailForm.knowledgePointId = null
    detailForm.knowledgePointName = ''
    
    // 重置试题数量和总分数
    formData.questionCount = 0
    formData.totalScore = 0
  }
}

// 加载编辑数据
const loadEditData = () => {
  if (props.isEdit && props.examPlan) {
    // 加载详情数据
    if (props.examPlan.details && props.examPlan.details.length > 0) {
      formData.details = JSON.parse(JSON.stringify(props.examPlan.details))
      // 更新下一个序号
      detailForm.questionOrder = formData.details.length + 1
      // 更新试题数量和总分数
      calculateTotals()
    }
  }
}

// 监听难度选择变化
const handleHardLevelChange = (value) => {
  // 重置知识点选择
  detailForm.knowledgePointId = null
  detailForm.knowledgePointName = ''
}

// 组件挂载时获取数据
onMounted(() => {
  fetchBigQuestions()
  // 如果是编辑模式，加载编辑数据
  loadEditData()
})

// 暴露方法给父组件
defineExpose({
  resetForm
})
</script>

<template>
  <div>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="100px"
    class="exam-plan-form"
  >
    <!-- 基本信息 -->
    <el-form-item label="方案名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入方案名称" />
    </el-form-item>
    
    <el-form-item label="描述" prop="description">
      <el-input 
        v-model="formData.description" 
        type="textarea" 
        :rows="3" 
        placeholder="请输入方案描述" 
      />
    </el-form-item>
    
    <!-- 统计信息 -->
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="试题数量">
          <el-input v-model="formData.questionCount" disabled />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="总分数">
          <el-input v-model="formData.totalScore" disabled />
        </el-form-item>
      </el-col>
    </el-row>
    
    <!-- 详情列表 -->
    <div class="details-section">
      <div class="section-header">
        <h3>方案详情</h3>
      </div>
      
      <!-- 已添加的详情列表 -->
      <el-table v-if="formData.details.length > 0" :data="formData.details" border class="details-table">
        <el-table-column prop="questionOrder" label="序号" width="80" />
        <el-table-column label="大题" width="150">
          <template #default="{row}">
            {{ row.bigQuestionName }}
          </template>
        </el-table-column>
        <el-table-column label="题型" width="150">
          <template #default="{row}">
            {{ row.questionTypeName }}
          </template>
        </el-table-column>
        <el-table-column label="难度" width="100">
          <template #default="{row}">
            <el-tag 
              :type="row.hardLevel === '易' || row.hardLevel === 'EASY' ? 'success' : (row.hardLevel === '中' || row.hardLevel === 'MEDIUM' ? 'warning' : 'danger')"
            >
              {{ row.hardLevel === '易' || row.hardLevel === 'EASY' ? '易' : (row.hardLevel === '中' || row.hardLevel === 'MEDIUM' ? '中' : '难') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="知识点" width="150">
          <template #default="{row}">
            {{ row.knowledgePointName }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分值" width="80" />
        <el-table-column label="操作" width="100">
          <template #default="{$index}">
            <el-button 
              link 
              type="danger" 
              size="small" 
              @click="removeDetail($index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加详情表单 -->
      <div class="add-detail-form">
        <el-divider content-position="left">添加详情项</el-divider>
        
        <el-form label-width="100px" class="detail-form">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="序号">
                <el-input-number v-model="detailForm.questionOrder" :min="1" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="大题" required>
                <div class="selector-input">
                  <el-input v-model="detailForm.bigQuestionName" placeholder="请选择大题" readonly />
                  <el-button type="primary" @click="openBigQuestionDialog">选择</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="题型" required>
                <div class="selector-input">
                  <el-input v-model="detailForm.questionTypeName" placeholder="请选择题型" readonly />
                  <el-button type="primary" @click="openQuestionTypeDialog">选择</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="难度" required>
                <el-select 
                  v-model="detailForm.hardLevel" 
                  placeholder="选择难度" 
                  @change="handleHardLevelChange"
                  :disabled="!detailForm.questionTypeId"
                >
                  <el-option 
                    v-for="option in hardLevelOptions" 
                    :key="option.hardLevel" 
                    :label="option.hardLevel === '易' ? '容易' : (option.hardLevel === '中' ? '中等' : '困难')" 
                    :value="option.hardLevel" 
                    :disabled="option.questionCount === 0"
                  >
                    <span>{{ option.hardLevel === '易' ? '容易' : (option.hardLevel === '中' ? '中等' : '困难') }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      试题数量: {{ option.questionCount }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="知识点" required>
                <div class="selector-input">
                  <el-input v-model="detailForm.knowledgePointName" placeholder="请选择知识点" readonly />
                  <el-button type="primary" @click="openKnowledgePointDialog">选择</el-button>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="分值" required>
                <el-input-number v-model="detailForm.score" :min="0.5" :precision="1" :step="0.5" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item>
            <el-button type="primary" @click="addDetail">添加详情</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    
    <!-- 表单操作按钮 -->
    <el-form-item class="form-actions">
      <el-button @click="cancel">取消</el-button>
      <el-button @click="saveAsDraft">保存为草稿</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
    </el-form-item>
  </el-form>
  
  <!-- 大题选择对话框 -->
  <el-dialog
    v-model="bigQuestionDialogVisible"
    title="选择大题"
    width="50%"
  >
    <el-table :data="bigQuestionList" border style="width: 100%" height="400px">
      <el-table-column label="序号" width="80">
        <template #default="{$index}">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="大题名称" />
      <el-table-column prop="questionCount" label="试题数量" width="100">
        <template #default="{row}">
          <el-tag :type="row.questionCount > 0 ? 'success' : 'info'">{{ row.questionCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{row}">
          <el-button 
            type="primary" 
            link 
            @click="selectBigQuestion(row)" 
            :disabled="row.questionCount === 0"
          >
            选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  
  <!-- 题型选择对话框 -->
  <el-dialog
    v-model="questionTypeDialogVisible"
    title="选择题型"
    width="50%"
  >
    <el-table :data="questionTypeList" border style="width: 100%" height="400px">
      <el-table-column label="序号" width="80">
        <template #default="{$index}">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="题型名称" />
      <el-table-column prop="questionCount" label="试题数量" width="100">
        <template #default="{row}">
          <el-tag :type="row.questionCount > 0 ? 'success' : 'info'">{{ row.questionCount }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{row}">
          <el-button 
            type="primary" 
            link 
            @click="selectQuestionType(row)" 
            :disabled="row.questionCount === 0"
          >
            选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
  
  <!-- 知识点选择对话框 -->
  <el-dialog
    v-model="knowledgePointDialogVisible"
    title="选择知识点"
    width="50%"
    :close-on-click-modal="false"
  >
    <KnowledgePointTree
      :subject-id="props.subjectId"
      :big-question-id="detailForm.bigQuestionId"
      :question-type-id="detailForm.questionTypeId"
      :hard-level="detailForm.hardLevel"
      @select="selectKnowledgePoint"
    />
  </el-dialog>
</div>
</template>

<style scoped>
.exam-plan-form {
  max-width: 100%;
}

.details-section {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
}

.section-header {
  margin-bottom: 15px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.details-table {
  margin-bottom: 20px;
}

.add-detail-form {
  margin-top: 20px;
}

.detail-form {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
}

.form-actions {
  margin-top: 30px;
  text-align: right;
}

/* 选择器输入框样式 */
.selector-input {
  display: flex;
  align-items: center;
}

.selector-input .el-input {
  flex: 1;
  margin-right: 10px;
}

.selector-input .el-button {
  flex-shrink: 0;
}
</style>